package JavaSE;
import java.util.Scanner;
//自定义异常类是类，所以需要先定义这样的类，后面才能使用自定义异常类

//定义用户名错误异常类
class UserNameException extends Exception{
    public UserNameException(){
        super("用户名错误！");
    }
}

//定义密码错误异常类
class PasswordException extends Exception{
    public PasswordException(){
        super("密码错误！");
    }
}

class Login{
    private String username = "admin";
    private String password = "123456";

    public void login(String username,String password) throws UserNameException,PasswordException{
        if(!username.equals(this.username)){
            throw new UserNameException();
        }
        if(!password.equals(this.password)){
            throw new PasswordException();
        }
        System.out.println("登陆成功！");
    }
}
public class time20250504_自定义异常类 {
    public static void main(String[] args){
    Login login = new Login();
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String username = scanner.nextLine();
        System.out.print("请输入密码:");
        String password = scanner.nextLine();
        try{
        login.login(username,password);
    }catch(UserNameException e){
//getMessage方法会调用自定义异常类UserNameException类中的UserNameException方法，然后就会打印出"用户名错误！"
        System.out.println(e.getMessage());
    }catch(PasswordException e){
        System.out.println(e.getMessage());//同上
    }

     //关闭Scanner对象，释放资源
     scanner.close();
    }
}
